package com.infore.airsupervise.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.MainFragAdapter;
import com.infore.airsupervise.app.AppManager;
import com.infore.airsupervise.other.listener.MainFragBtnClickListener;
import com.infore.airsupervise.service.JobHandleService;
import com.infore.airsupervise.service.MainService;
import com.infore.airsupervise.service.SubService;
import com.infore.airsupervise.ui.fragment.EventsFragment;
import com.infore.airsupervise.ui.fragment.LawFragment;
import com.infore.airsupervise.ui.fragment.MainDrawerFragment;
import com.infore.airsupervise.ui.fragment.MapFragment;
import com.infore.airsupervise.ui.fragment.RealTimeFragment;
import com.infore.airsupervise.ui.fragment.StatisticsFragment;
import com.infore.airsupervise.ui.widget.NoScrollViewPager;
import com.infore.airsupervise.utils.ToastUtil;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnTabSelectListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 主界面
 * <p>
 * 作者: dingxinlin
 * 创建时间: 2017/8/14 16:21
 */
@RuntimePermissions
public class MainActivity extends BaseActivity implements MainFragBtnClickListener {

    @BindView(R.id.main_view_pager)
    NoScrollViewPager mainViewPager;
    @BindView(R.id.main_tab_bar)
    BottomBar mainTabBar;
    @BindView(R.id.drawer_container)
    FrameLayout drawerContainer;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;

    // 抽屉的开关
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private List<Fragment> fragments = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        initView();
        initTabBar();


        // 申请权限
        MainActivityPermissionsDispatcher.applyPermissionWithCheck(MainActivity.this);
    }

    /**
     * 初始化title bar
     */
    private void initView() {
        // 添加抽屉Fragment
        MainDrawerFragment drawerFrag = new MainDrawerFragment();
        getSupportFragmentManager().beginTransaction().replace(R.id.drawer_container, drawerFrag).commit();
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, 0, 0);
        drawerLayout.addDrawerListener(actionBarDrawerToggle);

        // 初始化View Pager
        MapFragment mapFrag = new MapFragment(this);
        RealTimeFragment warningFragment = new RealTimeFragment(this);
        StatisticsFragment chartFrag = new StatisticsFragment(this);
        EventsFragment eventsFragment = new EventsFragment();
        eventsFragment.setMainFragBtnClickListener(this);
        //LawFragment lawFrag = new LawFragment(this);
        fragments.add(mapFrag);
        fragments.add(warningFragment);
        fragments.add(chartFrag);
        fragments.add(eventsFragment);
        MainFragAdapter fragAdapter = new MainFragAdapter(getSupportFragmentManager(), fragments, null);
        mainViewPager.setAdapter(fragAdapter);
    }

    /**
     * 初始化底部导航栏
     */
    private void initTabBar() {
        mainTabBar.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelected(@IdRes int tabId) {
                switch (tabId) {
                    case R.id.tab_map:
                        mainViewPager.setCurrentItem(0);
                        break;
                    case R.id.tab_realtime:
                        mainViewPager.setCurrentItem(1);
                        break;
                    case R.id.tab_statistics:
                        mainViewPager.setCurrentItem(2);
                        break;
                    case R.id.tab_event:
                        mainViewPager.setCurrentItem(3);
                        break;
                }
            }
        });
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        actionBarDrawerToggle.syncState();
    }

    /**
     * 展示抽屉布局
     */
    @Override
    public void onShowDrawerBtnClick() {
        if (!drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.openDrawer(Gravity.LEFT);
        } else {
            drawerLayout.closeDrawers();
        }
    }

    /**
     * 缩放按钮点击
     *
     * @param isFullScreen
     */
    @Override
    public void onZoomBtnClick(boolean isFullScreen) {
        mainTabBar.setVisibility(isFullScreen ? View.GONE : View.VISIBLE);
    }

    /**
     * 双击回退按钮退出APP
     */
    private long mExitTime = System.currentTimeMillis();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (System.currentTimeMillis() - mExitTime < 1500) {
                AppManager.getInstance().AppExit(ctx);
            } else {
                ToastUtil.showShort(ctx, "再按一次退出应用");
                mExitTime = System.currentTimeMillis();
            }
        }
        return false;
    }

    /*-----------------------------------------申请权限-------------------------------------------------------*/

    /**
     * 申请所有权限
     */
    @NeedsPermission({
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.RECORD_AUDIO})
    void applyPermission() {
        Log.d("DXL", "必要权限获取成功~");
        // 启动服务
        this.startService(new Intent(this, MainService.class));
        this.startService(new Intent(this, SubService.class));
        // 系统版本大于/等于5.0时，启动JobService
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            this.startService(new Intent(this, JobHandleService.class));
        }

    }

    /**
     * 解释为什么需要这个权限
     *
     * @param request
     */
    @OnShowRationale({
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO})
    void showRationaleForRecord(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("APP需要相关权限，拒绝后部分功能将不可用")
                .show();
    }

    /**
     * 勾选了不再提示禁止后调用
     */
    @OnNeverAskAgain({
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.RECORD_AUDIO})
    void onRecordNeverAskAgain() {
        new AlertDialog.Builder(this)
                .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 打开系统设置权限
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", MainActivity.this.getPackageName(), null);
                        intent.setData(uri);
                        MainActivity.this.startActivity(intent);

                        dialog.cancel();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("您已经禁止了相关权限,是否现在去开启？")
                .show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
